package com.hori3d.rc;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.net.Socket;
import java.net.UnknownHostException;
import java.nio.ByteBuffer;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;

import com.hori3d.rc.R.id;
import com.hori3d.rc.adapter.ViewPagerAdapter;
import com.hori3d.rc.bean.Printer;
import com.hori3d.rc.service.BridgeService;
import com.hori3d.rc.service.BridgeService.AddCameraInterface;
import com.hori3d.rc.service.BridgeService.CallBackMessageInterface;
import com.hori3d.rc.service.BridgeService.IpcamClientInterface;
import com.hori3d.rc.service.BridgeService.PlayInterface;
import com.hori3d.rc.utils.Logger;
import com.hori3d.rc.utils.SimpleNetTask;
import com.hori3d.rc.utils.Utils;
import com.ipcamera.demo.utils.AudioPlayer;
import com.ipcamera.demo.utils.ContentCommon;
import com.ipcamera.demo.utils.CustomAudioRecorder;
import com.ipcamera.demo.utils.CustomBuffer;
import com.ipcamera.demo.utils.CustomBufferData;
import com.ipcamera.demo.utils.CustomBufferHead;
 
import com.ipcamera.demo.utils.MyRender;
import com.ipcamera.demo.utils.SystemValue;
import com.ipcamera.demo.utils.CustomAudioRecorder.AudioRecordResult;

import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.res.Configuration;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.Matrix;
import android.graphics.PointF;
import android.graphics.Shader.TileMode;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.ColorDrawable;
import android.graphics.drawable.Drawable;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.opengl.GLSurfaceView;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.os.StrictMode;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.util.FloatMath;
import android.util.Log;
import android.view.Display;
import android.view.GestureDetector;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;  
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.view.GestureDetector.OnGestureListener;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.HorizontalScrollView;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.PopupWindow.OnDismissListener;
import android.widget.SeekBar.OnSeekBarChangeListener;
import vstc2.nativecaller.NativeCaller;  
  



public class CameraFragment extends Fragment implements  AddCameraInterface
, OnItemSelectedListener, IpcamClientInterface,CallBackMessageInterface
,PlayInterface ,AudioRecordResult {  

	
	private LayoutInflater mInflater;  
	private Button powerOffBt;
	private ImageView autoPowerOffIV;
	private RelativeLayout autoPowerOffRL;
	private boolean isAutoPowerOff=false; 
	private ProgressBar progressBar;
	
	private static final int SEARCH_TIME = 3000;
	private int option = ContentCommon.INVALID_OPTION;
	private int CameraType = ContentCommon.CAMERA_TYPE_MJPEG;
 
	//private SearchListAdapter listAdapter = null;
	private ProgressDialog progressdlg = null;
 
	private MyBroadCast receiver;
 
	 
	private static final String STR_DID = "did";
	private static final String STR_MSG_PARAM = "msgparam";
	private MyWifiThread myWifiThread = null;
	private boolean blagg = false;
	private Intent intentbrod = null;
	private WifiInfo info = null;
	private int tag=0;
	boolean bthread = true;
 
   Timer fileTimer;
	
	
	//playActivity Attri
	private static final String LOG_TAG = "PlayActivity";
	private static final int AUDIO_BUFFER_START_CODE = 0xff00ff;
	//surfaceView控件
	private GLSurfaceView playSurface = null;
	int orientation=Configuration.ORIENTATION_PORTRAIT;//屏幕方向
	//视频数据
	private byte[] videodata = null;
	private int videoDataLen = 0;
	public int nVideoWidths = 0;
	public int nVideoHeights = 0;
	
	
	private View progressView = null;
	private boolean bProgress = true;
	private final int BRIGHT = 1;//亮度标志 
	private final int CONTRAST = 2;//对比度标�?
	private int nResolution = 0;//分辨率�??
	private int nBrightness = 0;//亮度�?
	private int nContrast = 0;//对比�?

	private boolean bInitCameraParam = false;
	private boolean bManualExit = false;
	private TextView textosd = null;
	private String strName = null;
	private String strDID = null;
	private View osdView = null;
	private boolean bDisplayFinished = true;
	private CustomBuffer AudioBuffer = null;
	private AudioPlayer audioPlayer = null;
	private boolean bAudioStart = false;

	private boolean isLeftRight = false;
	private boolean isUpDown = false;
	
	private boolean isHorizontalMirror = false;
	private boolean isVerticalMirror = false;
	private boolean isUpDownPressed = false;
	private boolean isShowtoping = false;
	private ImageView videoViewPortrait, videoViewLandscape;
	private ImageView videoViewStandard;
	//顶部控件声明
	private HorizontalScrollView bottomView;
	private ImageButton ptzAudio,ptztalk,ptzDefaultSet,ptzBrightness,ptzContrast,ptzTake_photos,ptzTake_vodeo,ptzResolutoin,preset;
	private int nStreamCodecType;//分辨率格�?
	
	
	private PopupWindow controlWindow;//设备方向控制提示控件
	private PopupWindow mPopupWindowProgress;//进度条控�?
	private PopupWindow presetBitWindow;//预置位面�?
	private PopupWindow resolutionPopWindow;//分辨率面�?
	//上下左右提示文本
	private TextView control_item;
	//正在控制设备
	private boolean isControlDevice = false;
	
	private String stqvga = "qvga";
	private String stvga = "vga";
	private String stqvga1 = "qvga1";
	private String stvga1 = "vga1";
	private String stp720 = "p720";
	private String sthigh = "high";
	private String stmiddle ="middle";
	private String stmax = "max";
	
	//预位置设�?
	private Button[] btnLeft = new Button[16];
	private Button[] btnRigth = new Button[16];
	private Button  btnBack;
	
	private ViewPager prePager;
	private List<View> listViews;
	//分辨率标识符
	private boolean ismax = false;
	private boolean ishigh = false;
	private boolean isp720 = false;
	private boolean ismiddle = false;
	private boolean isqvga1 = false;
	private boolean isvga1 = false;
	private boolean isqvga = false;
	private boolean isvga = false;
	
	private Animation showAnim;
	private boolean isTakepic = false;
	private boolean isTalking = false;//是否在说�?
	private boolean isMcriophone = false;//是否�?
 
	public boolean isH264 = false;//是否是H264格式标志
	private boolean isTakeVideo = false;
	private long videotime = 0;// 录每张图片的时间
	
	private Animation dismissAnim;
	private int timeTag = 0;
	private int timeOne = 0;
	private int timeTwo = 0;
	private ImageButton button_back;
	private BitmapDrawable drawable = null;
	private boolean bAudioRecordStart = false;
	//送话�?
	private CustomAudioRecorder customAudioRecorder;
	private MyRender myRender;
	
	
	View view;
	
	
	
	
	private Handler Handler = new Handler() {
		public void handleMessage(Message msg) {
			if(msg.what==201)
		   Utils.toast(getActivity(), "nativecaller初始化成�?");
		}
	};
	
	
	
	class MyTimerTask extends TimerTask {

		public void run() {
			updateListHandler.sendEmptyMessage(100000);
		}
	};

	class MyWifiThread extends Thread {
		@Override
		public void run() {
			while (blagg == true) {
				super.run();

				updateListHandler.sendEmptyMessage(100000);
				try {
					Thread.sleep(1000);
				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}
	}

	private class MyBroadCast extends BroadcastReceiver {

		@Override
		public void onReceive(Context arg0, Intent arg1) {
			
			//getActivity().finish();
			Log.d("ip", "AddCameraActivity.this.finish()");
		}

	}

	class StartPPPPThread implements Runnable {
		@Override
		public void run() {
			try {
				
				Thread.sleep(100);
				startCameraPPPP();
				
			} catch (Exception e) {

			}
		}
	}
	private void startCameraPPPP() {
		try {
			Thread.sleep(100);
		} catch (Exception e) {
		}
		int result = NativeCaller.StartPPPP(SystemValue.deviceId, SystemValue.deviceName,
				SystemValue.devicePass,1,"");
		Utils.toast(getActivity(), "startPPPP结果:"+result);
		 
  
	}

	private void stopCameraPPPP()
	{
		NativeCaller.StopPPPP(SystemValue.deviceId);
	}
	
	Runnable updateThread = new Runnable() {

		public void run() {
			NativeCaller.StopSearch();
			progressdlg.dismiss();
			Message msg = updateListHandler.obtainMessage();
			msg.what = 201;
			updateListHandler.sendMessage(msg);
		}
	};
	
	Handler updateListHandler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
//			if (msg.what == 1) {
//				listAdapter.notifyDataSetChanged();
//				if (listAdapter.getCount() > 0) {
//					AlertDialog.Builder dialog = new AlertDialog.Builder(
//							AddCameraActivity2.this);
//					dialog.setTitle(getResources().getString(
//							R.string.add_search_result));
//					dialog.setPositiveButton(
//							getResources().getString(R.string.refresh),
//							new DialogInterface.OnClickListener() {
//
//								@Override
//								public void onClick(DialogInterface dialog,
//										int which) {
//									startSearch();
//								}
//							});
//					dialog.setNegativeButton(
//							getResources().getString(R.string.str_cancel), null);
//					dialog.setAdapter(listAdapter,
//							new DialogInterface.OnClickListener() {
//
//								@Override
//								public void onClick(DialogInterface dialog,
//										int arg2) {
//									Map<String, Object> mapItem = (Map<String, Object>) listAdapter
//											.getItemContent(arg2);
//									if (mapItem == null) {
//										return;
//									}
//
//									String strName = (String) mapItem
//											.get(ContentCommon.STR_CAMERA_NAME);
//									String strDID = (String) mapItem
//											.get(ContentCommon.STR_CAMERA_ID);
//									String strUser = ContentCommon.DEFAULT_USER_NAME;
//									String strPwd = ContentCommon.DEFAULT_USER_PWD;
//									userEdit.setText(strUser);
//									pwdEdit.setText(strPwd);
//									didEdit.setText(strDID);
//
//								}
//							});
//
//					dialog.show();
//				} else {
//					Utils.toast(getActivity(),R.string.add_search_no);
//					isSearched = false;// 
//				}
//			}
//			
//			
//			if(msg.what==2){
//				button_linkcamera.setVisibility(View.VISIBLE);
//			}
//			
		}
	};
	private WifiManager manager;

	public static String int2ip(long ipInt) {
		StringBuilder sb = new StringBuilder();
		sb.append(ipInt & 0xFF).append(".");
		sb.append((ipInt >> 8) & 0xFF).append(".");
		sb.append((ipInt >> 16) & 0xFF).append(".");
		sb.append((ipInt >> 24) & 0xFF);
		return sb.toString();
	}
	
Handler fileStatusHandler = new Handler() {
    public void handleMessage(Message msg) {
    	if(App.getInstance().getPrinter().isAutoPowerOff())
				autoPowerOffIV.setBackgroundResource(R.drawable.checked_checkbox);		
			else	
				autoPowerOffIV.setBackgroundResource(R.drawable.unchecked_checkbox);
	
    }
};
	
@Override  
public void onCreate(Bundle savedInstanceState) {  
super.onCreate(savedInstanceState);  
 
Intent intent = new Intent();
intent.setClass(getActivity(),BridgeService.class);
getActivity().startService(intent);



fileTimer = new Timer();
fileTimer.schedule(new TimerTask() {
	
	@Override
	public void run() {
		fileStatusHandler.sendEmptyMessage(0);
		
	}
}, 0, 20000);











new Thread(new Runnable() {
	@Override
	public void run() {
		try {
			NativeCaller.PPPPInitialOther("ADCBBFAOPPJAHGJGBBGLFLAGDBJJHNJGGMBFBKHIBBNKOKLDHOBHCBOEHOKJJJKJBPMFLGCPPJMJAPDOIPNL");
			Thread.sleep(3000);
			Message msg = new Message();
			mHandler.sendMessage(msg);
		} catch (Exception e) {

		}
	}
}).start();


progressdlg = new ProgressDialog(getActivity());
progressdlg.setProgressStyle(ProgressDialog.STYLE_SPINNER);
progressdlg.setMessage(getString(R.string.searching_tip));

manager = (WifiManager) getActivity().getSystemService(Context.WIFI_SERVICE);
BridgeService.setAddCameraInterface(this);
BridgeService.setCallBackMessage(this);
receiver = new MyBroadCast();
IntentFilter filter = new IntentFilter();
filter.addAction("finish");
getActivity().registerReceiver(receiver, filter);
intentbrod = new Intent("drop");



// ````````````````````````````````````````````


}  


void initPlayer(){
	

strName = SystemValue.deviceName;
strDID = SystemValue.deviceId;
disPlaywidth = getActivity().getWindowManager().getDefaultDisplay().getWidth();
//findView();
AudioBuffer = new CustomBuffer();
audioPlayer = new AudioPlayer(AudioBuffer);
customAudioRecorder=new CustomAudioRecorder(this);
//myvideoRecorder = new CustomVideoRecord(this, strDID);
BridgeService.setPlayInterface(this);
NativeCaller.StartPPPPLivestream(strDID, 10, 1);//确保不能重复start

getCameraParams();
 


	
}



  
@Override  
public View onCreateView(LayoutInflater inflater, ViewGroup container,  
Bundle savedInstanceState) {  
	mInflater = inflater;  
    view = inflater.inflate(R.layout.fragment_cam, container, false);
	 
	
        progressBar=(ProgressBar) view.findViewById(R.id.pb_cam_connect);
		//视频渲染画面控件
		playSurface = (GLSurfaceView) view.findViewById(R.id.mysurfaceview);

		playSurface.setLongClickable(true);//确保手势识别正确工作
		myRender = new MyRender(playSurface);
		playSurface.setRenderer(myRender);
		
		int width = getActivity().getWindowManager().getDefaultDisplay().getWidth();
		 
		FrameLayout.LayoutParams lp = new FrameLayout.LayoutParams(
				width, width * 3 / 4);
		lp.gravity = Gravity.TOP;
		playSurface.setLayoutParams(lp);
		
		
		videoViewPortrait = (ImageView) view.findViewById(R.id.vedioview);
		videoViewStandard = (ImageView) view.findViewById(R.id.vedioview_standard);
		
		progressView = (View) view.findViewById(R.id.progressLayout);
	
		powerOffBt=(Button) view.findViewById(id.bt_power_off);
		 powerOffBt.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				if(App.getInstance().getPrinter().getPrinterStatusCode()==Printer.PRINTER_STATUS_PRINTING)
				{
					AlertDialog.Builder builder=new AlertDialog.Builder(getActivity())
							.setTitle("提示")
							.setMessage("请先将打印暂停或停止，再尝试关机�?");
					builder.show();
					
				}	
				else
				{
					
					AlertDialog.Builder builder=new AlertDialog.Builder(getActivity())
							.setTitle("提示")
							.setMessage("确定要远程关闭打印机么？")
							.setNegativeButton(	"确认", new android.content.DialogInterface.OnClickListener() {
								
								public void onClick(DialogInterface dialog, int which) {
									// TODO Auto-generated method stub
									
									((MainActivity) getActivity()).sendQuery(Printer.CMD_POWER_OFF);	
									
								}
							})
					         .setPositiveButton("取消", new android.content.DialogInterface.OnClickListener() {
								
								public void onClick(DialogInterface dialog, int which) {
									// TODO Auto-generated method stub
									dialog.dismiss();
								}
							});
					builder.show();
					
 
				}
	 
			}
		});
		
		 
		
		autoPowerOffRL=(RelativeLayout)view.findViewById(id.rl_auto_power_off);
		
		
		
		
		
		autoPowerOffIV=(ImageView) view.findViewById(id.ib_auto_power_off);


 		autoPowerOffRL.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				isAutoPowerOff=!isAutoPowerOff;
				autoPowerOffIV.setBackgroundResource(0);
				if(isAutoPowerOff)
				{
					autoPowerOffIV.setBackgroundResource(R.drawable.checked_checkbox);;
					((MainActivity) getActivity()).sendQuery(Printer.CMD_AUTO_POWER_OFF);
				}
				else
				{
					autoPowerOffIV.setBackgroundResource(R.drawable.unchecked_checkbox);;
					((MainActivity) getActivity()).sendQuery(Printer.CMD_NO_AUTO_POWER_OFF);
				
				}
			}
		});
	
	
return view;
}

 @Override
public void onActivityCreated(Bundle savedInstanceState) {
	// TODO Auto-generated method stub
	super.onActivityCreated(savedInstanceState);
	connectCam();
}



private Handler PPPPMsgHandler = new Handler() {
	public void handleMessage(Message msg) {

		Bundle bd = msg.getData();
		int msgParam = bd.getInt(STR_MSG_PARAM);
		int msgType = msg.what;
		Log.i("aaa", "===="+msgType+"--msgParam:"+msgParam);
		String did = bd.getString(STR_DID);
		//Utils.toast(getActivity(), "PPPPMSG"+msgType+"");
		
		switch (msgType) {
		case ContentCommon.PPPP_MSG_TYPE_PPPP_STATUS:
			int resid;
			switch (msgParam) {
			case ContentCommon.PPPP_STATUS_CONNECTING://0  //正在连接
				resid = R.string.pppp_status_connecting;
				 progressBar.setVisibility(View.VISIBLE);
				Utils.toast(getActivity(), "正在连接摄像头");
				tag = 2;
				break;
			case ContentCommon.PPPP_STATUS_CONNECT_FAILED://3 //连接失败
				resid = R.string.pppp_status_connect_failed;
				 progressBar.setVisibility(View.GONE);
				Utils.toast(getActivity(), "连接摄像头失败");
			 
				tag = 0;
				break;
			case ContentCommon.PPPP_STATUS_DISCONNECT://4 // 未连摄像头
				resid = R.string.pppp_status_disconnect;
				 progressBar.setVisibility(View.GONE);
				Utils.toast("未连摄像头");
				tag = 0;
				break;
			case ContentCommon.PPPP_STATUS_INITIALING://1  //初始化中
				resid = R.string.pppp_status_initialing;
				 progressBar.setVisibility(View.VISIBLE);
				tag = 2;
				Utils.toast(getActivity(), "摄像头初始化成功");
				break;
			case ContentCommon.PPPP_STATUS_INVALID_ID://5 //无效Id
				resid = R.string.pppp_status_invalid_id;
				 progressBar.setVisibility(View.GONE);
				Utils.toast(getActivity(), "摄像头ID无效");
				tag = 0;
				break;
			case ContentCommon.PPPP_STATUS_ON_LINE://2 在线
				resid = R.string.pppp_status_online;
				 progressBar.setVisibility(View.GONE);
				 
				//摄像机在线之后读取摄像机类型
				String cmd="get_status.cgi?loginuse=admin&loginpas=" + SystemValue.devicePass
						+ "&user=admin&pwd=" + SystemValue.devicePass;
				NativeCaller.TransferMessage(did, cmd, 1);
				tag = 1;
				Utils.toast("摄像头在线");
				initPlayer();
				
				break;
			case ContentCommon.PPPP_STATUS_DEVICE_NOT_ON_LINE://6
				resid = R.string.device_not_on_line;
				 progressBar.setVisibility(View.GONE);
				Utils.toast("设备不在线");
				tag = 0;
				break;
			case ContentCommon.PPPP_STATUS_CONNECT_TIMEOUT://7
				resid = R.string.pppp_status_connect_timeout;
				 progressBar.setVisibility(View.GONE);
				Utils.toast("连接超时");
				tag = 0;
				break;
			case ContentCommon.PPPP_STATUS_CONNECT_ERRER://8
				resid =R.string.pppp_status_pwd_error;
				 progressBar.setVisibility(View.GONE);
				Utils.toast("连接错误");
				tag = 0;
				break;
			default:
				resid = R.string.pppp_status_unknown;
			}
			//cameraStateTV.setText(getResources().getString(resid));
			if (msgParam == ContentCommon.PPPP_STATUS_ON_LINE) {
				NativeCaller.PPPPGetSystemParams(did,
						ContentCommon.MSG_TYPE_GET_PARAMS);
			}
			if (msgParam == ContentCommon.PPPP_STATUS_INVALID_ID
					|| msgParam == ContentCommon.PPPP_STATUS_CONNECT_FAILED
					|| msgParam == ContentCommon.PPPP_STATUS_DEVICE_NOT_ON_LINE
					|| msgParam == ContentCommon.PPPP_STATUS_CONNECT_TIMEOUT
					|| msgParam == ContentCommon.PPPP_STATUS_CONNECT_ERRER) {
				 
				NativeCaller.StopPPPP(did);
				 
			}
			break;
		case ContentCommon.PPPP_MSG_TYPE_PPPP_MODE:
			break;

		}

	}
};


@Override
public void BSMsgNotifyData(String did, int type, int param) {
	Log.d("ip", "type:" + type + " param:" + param);
	Bundle bd = new Bundle();
	Message msg = PPPPMsgHandler.obtainMessage();
	msg.what = type;
	bd.putInt(STR_MSG_PARAM, param);
	bd.putString(STR_DID, did);
	msg.setData(bd);
	PPPPMsgHandler.sendMessage(msg);
	if (type == ContentCommon.PPPP_MSG_TYPE_PPPP_STATUS) {
		intentbrod.putExtra("ifdrop", param);
		getActivity().sendBroadcast(intentbrod);
	}

}

@Override
public void BSSnapshotNotify(String did, byte[] bImage, int len) {
	// TODO Auto-generated method stub
	Log.i("ip", "BSSnapshotNotify---len"+len);
}

@Override
public void callBackUserParams(String did, String user1, String pwd1,
		String user2, String pwd2, String user3, String pwd3) {
	// TODO Auto-generated method stub

}

@Override
public void CameraStatus(String did, int status) {
  
}

@Override
public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2,
		long arg3) {
	// TODO Auto-generated method stub

}

@Override
public void onNothingSelected(AdapterView<?> arg0) {
	// TODO Auto-generated method stub

}

@Override
public void CallBackGetStatus(String did, String resultPbuf, int cmd) {
	// TODO Auto-generated method stub
	if (cmd == ContentCommon.CGI_IEGET_STATUS) {
		String cameraType = spitValue(resultPbuf, "upnp_status=");
		int intType = Integer.parseInt(cameraType);
		int type14 = (int) (intType >> 16) & 1;// 14�? 来判断是否报警联动摄像机
		if (intType == 2147483647) {// 特殊�?
			type14 = 0;
		}
		
		if(type14==1){
			updateListHandler.sendEmptyMessage(2);
		}
		
	}
}

private String spitValue(String name, String tag) {
	String[] strs = name.split(";");
	for (int i = 0; i < strs.length; i++) {
		String str1 = strs[i].trim();
		if (str1.startsWith("var ")) {
			str1 = str1.substring(4, str1.length());
		}
		if (str1.startsWith(tag)) {
			String result = str1.substring(str1.indexOf("=") + 1);
			return result;
		}
	}
	return -1 + "";
}

@Override
public void callBackSearchResultData(int cameraType, String strMac, String strName, String strDeviceID,
		String strIpAddr, int port) {
	// TODO Auto-generated method stub
	
}

@Override
public void onResume() {
	// TODO Auto-generated method stub
	super.onResume();
 
}


public void setUserVisibleHint(boolean isVisibleToUser) {
    super.setUserVisibleHint(isVisibleToUser);
    if (isVisibleToUser) {
         Utils.toast(getActivity(), "可见");
    } else {
        Utils.toast(getActivity(), "不可�?");
    }
}



private void connectCam() {
 
	SystemValue.deviceName = ((MainActivity)getActivity()).m3Dprinter.getCam_Uname();
	SystemValue.deviceId =((MainActivity)getActivity()).m3Dprinter.getCam_id();// 
	SystemValue.devicePass = ((MainActivity)getActivity()).m3Dprinter.getCam_pw();// 
	BridgeService.setIpcamClientInterface(this);
	NativeCaller.Init();
	new Thread(new StartPPPPThread()).start();
}


 

private void showToast(int i)
{
	Toast.makeText(getActivity(), i, Toast.LENGTH_SHORT).show();
}


//设置视频可见
private void setViewVisible() {
	if (bProgress)
	{
		bProgress = false;
		progressView.setVisibility(View.INVISIBLE);
		
		getCameraParams();
	}
}

@Override
public void onStart() {
	// TODO Auto-generated method stub
	super.onStart();
	int orientation=getResources().getConfiguration().orientation;
}




int disPlaywidth;
private Bitmap mBmp;
private Handler mHandler = new Handler()
{

	public void handleMessage(Message msg)
    {       
		    int width=0;
            int height=0;
		    Logger.e(msg.toString());
			if (msg.what == 1 || msg.what == 2) {
				setViewVisible();
		   
		    if(getActivity()!=null)
			{width = getActivity().getWindowManager().getDefaultDisplay().getWidth();
		    height = getActivity().getWindowManager().getDefaultDisplay().getHeight();
			}
			switch (msg.what) {
			case 1: // h264	
			
			{
				if (reslutionlist.size() == 0) {
					if (nResolution == 0) {
						ismax = true;
						ismiddle = false;
						ishigh = false;
						isp720 = false;
						isqvga1 = false;
						isvga1 = false;
						addReslution(stmax, ismax);
					} else if (nResolution == 1) {
						ismax = false;
						ismiddle = false;
						ishigh = true;
						isp720 = false;
						isqvga1 = false;
						isvga1 = false;
						addReslution(sthigh, ishigh);
					} else if (nResolution == 2) {
						ismax = false;
						ismiddle = true;
						ishigh = false;
						isp720 = false;
						isqvga1 = false;
						isvga1 = false;
						addReslution(stmiddle, ismiddle);
					} else if (nResolution == 3) {
						ismax = false;
						ismiddle = false;
						ishigh = false;
						isp720 = true;
						isqvga1 = false;
						isvga1 = false;
						addReslution(stp720, isp720);
						nResolution = 3;
					} else if (nResolution == 4) {
						ismax = false;
						ismiddle = false;
						ishigh = false;
						isp720 = false;
						isqvga1 = false;
						isvga1 = true;
						addReslution(stvga1, isvga1);
					} else if (nResolution == 5) {
						ismax = false;
						ismiddle = false;
						ishigh = false;
						isp720 = false;
						isqvga1 = true;
						isvga1 = false;
						addReslution(stqvga1, isqvga1);
					}
				} else {
					if (reslutionlist.containsKey(strDID))
					{
						getReslution();
					} else {
						if (nResolution == 0) {
							ismax = true;
							ismiddle = false;
							ishigh = false;
							isp720 = false;
							isqvga1 = false;
							isvga1 = false;
							addReslution(stmax, ismax);
						} else if (nResolution == 1) {
							ismax = false;
							ismiddle = false;
							ishigh = true;
							isp720 = false;
							isqvga1 = false;
							isvga1 = false;
							addReslution(sthigh, ishigh);
						} else if (nResolution == 2) {
							ismax = false;
							ismiddle = true;
							ishigh = false;
							isp720 = false;
							isqvga1 = false;
							isvga1 = false;
							addReslution(stmiddle, ismiddle);
						} else if (nResolution == 3) {
							ismax = false;
							ismiddle = false;
							ishigh = false;
							isp720 = true;
							isqvga1 = false;
							isvga1 = false;
							addReslution(stp720, isp720);
							nResolution = 3;
						} else if (nResolution == 4) {
							ismax = false;
							ismiddle = false;
							ishigh = false;
							isp720 = false;
							isqvga1 = false;
							isvga1 = true;
							addReslution(stvga1, isvga1);
						} else if (nResolution == 5) {
							ismax = false;
							ismiddle = false;
							ishigh = false;
							isp720 = false;
							isqvga1 = true;
							isvga1 = false;
							addReslution(stqvga1, isqvga1);
						}
					}

				}

		 
				if (orientation == Configuration.ORIENTATION_PORTRAIT) 
				{
					FrameLayout.LayoutParams lp = new FrameLayout.LayoutParams(
							width, width * 3 / 4);
					lp.gravity = Gravity.TOP;
					playSurface.setLayoutParams(lp);
				}
				else if (orientation == Configuration.ORIENTATION_LANDSCAPE)
				{
					FrameLayout.LayoutParams lp = new FrameLayout.LayoutParams(
							width, height);
					lp.gravity = Gravity.CENTER;
					playSurface.setLayoutParams(lp);
				}
				myRender.writeSample(videodata, nVideoWidths, nVideoHeights);
			}
				break;
			case 2: // JPEG
			{
				if (reslutionlist.size() == 0) {
					if (nResolution == 1) {
						isvga = true;
						isqvga = false;
						addReslution(stvga, isvga);
					} else if (nResolution == 0) {
						isqvga = true;
						isvga = false;
						addReslution(stqvga, isqvga);
					}
				} else {
					if (reslutionlist.containsKey(strDID)) {
						getReslution();
					} else {
						if (nResolution == 1) {
							isvga = true;
							isqvga = false;
							addReslution(stvga, isvga);
						} else if (nResolution == 0) {
							isqvga = true;
							isvga = false;
							addReslution(stqvga, isqvga);
						}
					}
				}
				mBmp = BitmapFactory.decodeByteArray(videodata, 0,
						videoDataLen);
				if (mBmp == null) {
					bDisplayFinished = true;
					return;
				}
			 
				nVideoWidths = mBmp.getWidth();
				nVideoHeights = mBmp.getHeight();

				if (getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT) {
					// Bitmap
					Bitmap bitmap = Bitmap.createScaledBitmap(mBmp, width,
							width * 3 / 4, true);
					videoViewLandscape.setVisibility(View.GONE);
					videoViewPortrait.setVisibility(View.VISIBLE);
					videoViewPortrait.setImageBitmap(bitmap);

				} else if (getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE) {
					Bitmap bitmap = Bitmap.createScaledBitmap(mBmp, width,
							height, true);
					videoViewPortrait.setVisibility(View.GONE);
					videoViewLandscape.setVisibility(View.VISIBLE);
					videoViewLandscape.setImageBitmap(bitmap);
				}

			}
				break;
			default:
				break;
			}
		   if (msg.what == 1 || msg.what == 2)
		   {
				bDisplayFinished = true;
		   }	
	 }

}
	
};

private void getCameraParams() {

	NativeCaller.PPPPGetSystemParams(strDID,
			ContentCommon.MSG_TYPE_GET_CAMERA_PARAMS);
}
 


 
//
//@Override
//public boolean onKeyDown(int keyCode, KeyEvent event) {
//	if(mPopupWindowProgress != null && mPopupWindowProgress.isShowing())
//	{
//		mPopupWindowProgress.dismiss();
//	}
//	if(resolutionPopWindow != null && resolutionPopWindow.isShowing())
//	{
//		resolutionPopWindow.dismiss();
//	}
//	if (keyCode == KeyEvent.KEYCODE_BACK)
//	{
//		if (!bProgress)
//		{
//			Date date = new Date();
//			if (timeTag == 0) {
//				timeOne = date.getSeconds();
//				timeTag = 1;
//				showToast(R.string.main_show_back);
//			} else if (timeTag == 1) {
//				timeTwo = date.getSeconds();
//				if (timeTwo - timeOne <= 3) {
//					Intent intent = new Intent("finish");
//					getActivity().sendBroadcast(intent);
//				   	  
//					timeTag = 0;
//				} else {
//					timeTag = 1;
//					showToast(R.string.main_show_back);
//				}
//			}
//		} else {
//			showSureDialog();
//		}
//		return true;
//	}
//	if (keyCode == KeyEvent.KEYCODE_MENU) 
//	{
//		if (!bProgress) {
//			showTop();
//			showBottom();
//		} else {
//			getActivity().showSureDialog();
//		}
//	}
//	return super.onKeyDown(keyCode, event);
//}

protected void setResolution(int Resolution) {
	Log.d("tag", "setResolution resolution:" + Resolution);
	NativeCaller.PPPPCameraControl(strDID,16, Resolution);
}








private static final int NONE = 0;
private static final int DRAG = 1;
private static final int ZOOM = 2;

private int mode = NONE;
private float oldDist;
private Matrix matrix = new Matrix();
private Matrix savedMatrix = new Matrix();
private PointF start = new PointF();
private PointF mid = new PointF();
float mMaxZoom = 2.0f;
float mMinZoom = 0.3125f;
float originalScale;
float baseValue;
protected Matrix mBaseMatrix = new Matrix();
protected Matrix mSuppMatrix = new Matrix();
private Matrix mDisplayMatrix = new Matrix();
private final float[] mMatrixValues = new float[9];

protected void zoomTo(float scale, float centerX, float centerY)
{
	Log.d("zoomTo", "zoomTo scale:" + scale);
	if (scale > mMaxZoom) {
		scale = mMaxZoom;
	} else if (scale < mMinZoom) {
		scale = mMinZoom;
	}

	float oldScale = getScale();
	float deltaScale = scale / oldScale;
	Log.d("deltaScale", "deltaScale:" + deltaScale);
	mSuppMatrix.postScale(deltaScale, deltaScale, centerX, centerY);
	videoViewStandard.setScaleType(ImageView.ScaleType.MATRIX);
	videoViewStandard.setImageMatrix(getImageViewMatrix());
}

protected Matrix getImageViewMatrix() {
	mDisplayMatrix.set(mBaseMatrix);
	mDisplayMatrix.postConcat(mSuppMatrix);
	return mDisplayMatrix;
}

protected float getScale(Matrix matrix) {
	return getValue(matrix, Matrix.MSCALE_X);
}

protected float getScale() {
	return getScale(mSuppMatrix);
}

protected float getValue(Matrix matrix, int whichValue) {
	matrix.getValues(mMatrixValues);
	return mMatrixValues[whichValue];
}



private RelativeLayout topbg;
private Animation showTopAnim;
private Animation dismissTopAnim;
private boolean isFragmentPause=false;



 
//判断sd卡是否存�?
private boolean existSdcard() {
	if (Environment.getExternalStorageState().equals(
			Environment.MEDIA_MOUNTED)) {
		return true;
	} else {
		return false;
	}
}
 
 
//时间格式
private String getStrDate() {
	Date d = new Date();
	SimpleDateFormat f = new SimpleDateFormat("yyyy-MM-dd_HH_mm");
	String strDate = f.format(d);
	return strDate;
}
 
 
 
 
/*
 * 分辨率设�?
 */
private void showResolutionPopWindow() {
	
	if (resolutionPopWindow != null && resolutionPopWindow.isShowing()) {
		return;
	}
	if (nStreamCodecType == ContentCommon.PPPP_STREAM_TYPE_JPEG) {
		// jpeg
		LinearLayout layout = (LinearLayout) LayoutInflater.from(getActivity())
				.inflate(R.layout.ptz_resolution_jpeg, null);
		TextView qvga = (TextView) layout
				.findViewById(R.id.ptz_resolution_jpeg_qvga);
		TextView vga = (TextView) layout
				.findViewById(R.id.ptz_resolution_jpeg_vga);
		if (reslutionlist.size() != 0) {
			getReslution();
		}
		if (isvga) {
			vga.setTextColor(Color.RED);
		}
		if (isqvga) {
			qvga.setTextColor(Color.RED);
		}
//		qvga.setOnClickListener(this);
//		vga.setOnClickListener(this);
		resolutionPopWindow = new PopupWindow(layout, 100,
				WindowManager.LayoutParams.WRAP_CONTENT);
		int x_begin = getActivity().getWindowManager().getDefaultDisplay().getWidth() / 6;
		int y_begin = ptzResolutoin.getTop();
		resolutionPopWindow.showAtLocation( view.findViewById(R.id.play),
					Gravity.BOTTOM | Gravity.RIGHT, x_begin, y_begin);	

	} else {
		// h264
		LinearLayout layout = (LinearLayout) LayoutInflater.from(getActivity())
				.inflate(R.layout.ptz_resolution_h264, null);
		TextView qvga1 = (TextView) layout
				.findViewById(R.id.ptz_resolution_h264_qvga);
		TextView vga1 = (TextView) layout
				.findViewById(R.id.ptz_resolution_h264_vga);
		TextView p720 = (TextView) layout
				.findViewById(R.id.ptz_resolution_h264_720p);
		TextView middle = (TextView) layout
				.findViewById(R.id.ptz_resolution_h264_middle);
		TextView high = (TextView) layout
				.findViewById(R.id.ptz_resolution_h264_high);
		TextView max = (TextView) layout
				.findViewById(R.id.ptz_resolution_h264_max);

		if (reslutionlist.size() != 0) {
			getReslution();
		}
		if (ismax) {
			max.setTextColor(Color.RED);
		}
		if (ishigh) {
			high.setTextColor(Color.RED);
		}
		if (ismiddle) {
			middle.setTextColor(Color.RED);
		}
		if (isqvga1) {
			qvga1.setTextColor(Color.RED);
		}
		if (isvga1) {
			vga1.setTextColor(Color.RED);
		}
		if (isp720) {
			p720.setTextColor(Color.RED);
		}
//		high.setOnClickListener(this);
//		middle.setOnClickListener(this);
//		max.setOnClickListener(this);
//		qvga1.setOnClickListener(this);
//		vga1.setOnClickListener(this);
//		p720.setOnClickListener(this);
		resolutionPopWindow = new PopupWindow(layout, 100,
				WindowManager.LayoutParams.WRAP_CONTENT);
		Display display = ((WindowManager) getActivity().getSystemService(Context.WINDOW_SERVICE))
				.getDefaultDisplay();
	     	int oreation = display.getOrientation();
			int x_begin = getActivity().getWindowManager().getDefaultDisplay().getWidth() / 6;
			int y_begin = ptzResolutoin.getTop();
			resolutionPopWindow.showAtLocation(view.findViewById(R.id.play),
					Gravity.BOTTOM | Gravity.RIGHT, x_begin, y_begin + 60);
	
	}

}
/**
 * 获取reslution
 */
public static Map<String, Map<Object, Object>> reslutionlist = new HashMap<String, Map<Object, Object>>();
/**
 * 增加reslution
 */
private void addReslution(String mess, boolean isfast)
{
	if (reslutionlist.size() != 0) {
		if (reslutionlist.containsKey(strDID)) {
			reslutionlist.remove(strDID);
		}
	}
	Map<Object, Object> map = new HashMap<Object, Object>();
	map.put(mess, isfast);
	reslutionlist.put(strDID, map);
}
private void getReslution() {
	if (reslutionlist.containsKey(strDID)) {
		Map<Object, Object> map = reslutionlist.get(strDID);
		if (map.containsKey("qvga")) {
			isqvga = true;
		} else if (map.containsKey("vga")) {
			isvga = true;
		} else if (map.containsKey("qvga1")) {
			isqvga1 = true;
		} else if (map.containsKey("vga1")) {
			isvga1 = true;
		} else if (map.containsKey("p720")) {
			isp720 = true;
		} else if (map.containsKey("high")) {
			ishigh = true;
		} else if (map.containsKey("middle")) {
			ismiddle = true;
		} else if (map.containsKey("max")) {
			ismax = true;
		}
	}
}
/*
 * @param type
 * 亮度饱和对比�?
 */
private void setBrightOrContrast(final int type)
{

	if (!bInitCameraParam) {
		return;
	}
	int width = getActivity().getWindowManager().getDefaultDisplay().getWidth();
	LinearLayout layout = (LinearLayout) LayoutInflater.from(getActivity()).inflate(
			R.layout.brightprogress, null);
	SeekBar seekBar = (SeekBar) layout.findViewById(R.id.brightseekBar1);
	seekBar.setMax(255);
	switch (type) {
	case BRIGHT:
		seekBar.setProgress(nBrightness);
		break;
	case CONTRAST:
		seekBar.setProgress(nContrast);
		break;
	default:
		break;
	}
	seekBar.setOnSeekBarChangeListener(new OnSeekBarChangeListener() {

		@Override
		public void onStopTrackingTouch(SeekBar seekBar) {
			int progress = seekBar.getProgress();
			switch (type) {
			case BRIGHT:// 亮度
				nBrightness = progress;
				NativeCaller.PPPPCameraControl(strDID, BRIGHT, nBrightness);
				break;
			case CONTRAST:// 对比�?
				nContrast = progress;
				NativeCaller.PPPPCameraControl(strDID, CONTRAST, nContrast);
				break;
			default:
				break;
			}
		}

		@Override
		public void onStartTrackingTouch(SeekBar arg0) {

		}

		@Override
		public void onProgressChanged(SeekBar arg0, int progress,
				boolean arg2) {

		}
	});
	mPopupWindowProgress = new PopupWindow(layout, width / 2, 180);
	mPopupWindowProgress.showAtLocation(view.findViewById(R.id.play),
			Gravity.TOP, 0, 0);

}

@Override
public void onPause() {
 
	isFragmentPause=true;
 
	stopCameraPPPP();
	 
	NativeCaller.StopPPPPLivestream(SystemValue.deviceId);
 
    super.onPause();
}


@Override
public void onDestroy() {

	super.onDestroy();
}

/***
 * BridgeService callback 视频参数回调
 * 
 * **/
@Override
public void callBackCameraParamNotify(String did, int resolution,
		int brightness, int contrast, int hue, int saturation, int flip) {

	nBrightness = brightness;
	nContrast = contrast;
	nResolution = resolution;
	bInitCameraParam = true;
}

/***
 * BridgeService callback 视频数据流回�?
 * 
 * **/
@Override
public void callBaceVideoData(byte[] videobuf, int h264Data, int len,int width, int height) {
	Log.d("底层返回数据", "videobuf:"+videobuf+"--"+"h264Data"+h264Data+"len"+len+"width"+width+"height"+height);
	if (!bDisplayFinished)
		return;
	bDisplayFinished = false;
	videodata = videobuf;
	videoDataLen = len;
	Message msg = new Message();
	if (h264Data == 1) { // H264
		nVideoWidths = width;
		nVideoHeights = height;
		if (isTakepic) {
			isTakepic = false;
			byte[] rgb = new byte[width * height * 2];
			NativeCaller.YUV4202RGB565(videobuf, rgb, width, height);
			ByteBuffer buffer = ByteBuffer.wrap(rgb);
			mBmp = Bitmap
					.createBitmap(width, height, Bitmap.Config.RGB_565);
			mBmp.copyPixelsFromBuffer(buffer);
		 
		}
		isH264 = true;
		msg.what = 1;
	} else { // MJPEG
		msg.what = 2;
	}
	
	if(!isFragmentPause)
	mHandler.sendMessage(msg);
}

/***
 * BridgeService callback
 * 
 * **/
@Override
public void callBackMessageNotify(String did, int msgType, int param) {
	Log.d("tag", "MessageNotify did: " + did + " msgType: " + msgType
			+ " param: " + param);
	if (bManualExit)
		return;

	if (msgType == ContentCommon.PPPP_MSG_TYPE_STREAM) {
		nStreamCodecType = param;
		return;
	}

	if (msgType != ContentCommon.PPPP_MSG_TYPE_PPPP_STATUS) {
		return;
	}

	if (!did.equals(strDID)) {
		return;
	}

//	Message msg = new Message();
//	msg.what = 1;
//	msgHandler.sendMessage(msg);
}

/***
 * BridgeService callback
 * 
 * **/
@Override
public void callBackAudioData(byte[] pcm, int len) {
	Log.d(LOG_TAG, "AudioData: len :+ " + len);
	if (!audioPlayer.isAudioPlaying()) {
		return;
	}
	CustomBufferHead head = new CustomBufferHead();
	CustomBufferData data = new CustomBufferData();
	head.length = len;
	head.startcode = AUDIO_BUFFER_START_CODE;
	data.head = head;
	data.data = pcm;
	AudioBuffer.addData(data);
}

/***
 * BridgeService callback
 * 
 * **/
@Override
public void callBackH264Data(byte[] h264, int type, int size) {
	Log.d("tag", "CallBack_H264Data" + " type:" + type + " size:" + size);
	if (isTakeVideo) {
		Date date = new Date();
		long time = date.getTime();
		int tspan = (int) (time - videotime);
		Log.d("tag", "play  tspan:" + tspan);
		videotime = time;
		if (videoRecorder != null) {
			videoRecorder.VideoRecordData(type, h264, size, 0, tspan);
		}
	}
}
//对讲数据
@Override
public void AudioRecordData(byte[] data, int len) {
	// TODO Auto-generated method stub
	if (bAudioRecordStart && len > 0) {
		NativeCaller.PPPPTalkAudioData(strDID, data, len);
	}
}
//定义录像接口
	public void setVideoRecord(VideoRecorder videoRecorder)
	{
		this.videoRecorder = videoRecorder;
	}

	public VideoRecorder videoRecorder;

	public interface VideoRecorder
	{
		abstract public void VideoRecordData(int type, byte[] videodata,
				int width, int height, int time);
	}
}
 


 